﻿using JinKaiDataBasePlatform.Common.Helper;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Topshelf;

namespace SMS_Consumer_JinKaiDataBasePlatform
{
    public class SMS_Consumer : ServiceControl
    {
        private const string _logFileLocation = @"C:\temp\servicelog.txt";

        private IConnection connection;

        private IModel channel;

        private void Log(string logMessage)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(_logFileLocation));
            File.AppendAllText(_logFileLocation,
                DateTime.UtcNow.ToString() + " : " + logMessage + Environment.NewLine);
        }

        public bool Start(HostControl hostControl)
        {
            Log("Starting");

            string queueName = "SMSQueue";

            //创建连接工厂
            ConnectionFactory factory = new ConnectionFactory
            {
                UserName = "admin",//用户名
                Password = "admin123456",//密码
                HostName = "117.148.147.208",//rabbitmq ip
                VirtualHost = "SMS",
                Port = 5672,
            };

            //创建连接
            connection = factory.CreateConnection();
            //创建通道
            channel = connection.CreateModel();

            //事件基本消费者
            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);

            //接收到消息事件
            consumer.Received += (ch, ea) =>
            {
                var message = Encoding.UTF8.GetString(ea.Body);

                var smsModel = JsonConvert.DeserializeObject<SMSSendViewModel>(message);

                if (smsModel != null)
                {
                    if (smsModel.IsMul)
                    {
                        TXSMSHelper.SMS_SendMuti(smsModel.TemplateId, smsModel.PhoneNumbers, smsModel.Parameters);
                    }
                    else
                    {
                        TXSMSHelper.SMS_Send(smsModel.TemplateId, smsModel.Parameters, smsModel.PhoneNumbers[0]);
                    }
                }

                //确认该消息已被消费
                channel.BasicAck(ea.DeliveryTag, false);
            };
            //启动消费者 设置为手动应答消息
            channel.BasicConsume(queueName, false, consumer);

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            Log("Stopping");

            if (channel != null)
            {
                channel.Dispose();
            }

            if (connection != null)
            {
                connection.Close();
            }

            return true;
        }
    }
}
